<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, Refresh, Back } from '@element-plus/icons-vue'
import { addBill } from '@/api/bill'
import request from '@/utils/request'

const router = useRouter()
const billFormRef = ref()
const loading = ref(false)
const providerOptions = ref([])

// 表单数据
const billForm = reactive({
  billCode: '',
  productName: '',
  productDesc: '',
  productUnit: '',
  productCount: null,
  unitPrice: null,
  totalPrice: null,
  isPayment: 0,
  proName: '',
  createdBy: null
})

// 表单验证规则
const rules = {
  billCode: [
    { required: true, message: '请输入账单编码', trigger: 'blur' },
    { min: 3, max: 20, message: '账单编码长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '商品名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  productUnit: [
    { required: true, message: '请选择商品单位', trigger: 'change' }
  ],
  productCount: [
    { required: true, message: '请输入商品数量', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '商品数量必须大于0', trigger: 'blur' }
  ],
  unitPrice: [
    { required: true, message: '请输入单价', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '单价必须大于0', trigger: 'blur' }
  ],
  proName: [
    { required: true, message: '请选择供应商', trigger: 'change' }
  ],
  isPayment: [
    { required: true, message: '请选择是否付款', trigger: 'change' }
  ]
}

// 计算总金额
const calculateTotalPrice = () => {
  if (billForm.productCount && billForm.unitPrice) {
    billForm.totalPrice = Number((billForm.productCount * billForm.unitPrice).toFixed(2))
  }
}

// 获取供应商列表
const fetchProviders = () => {
  request({
    url: '/provider/list',
    method: 'get'
    // 不需要分页参数
  }).then(resp => {
    const responseData = resp.data;
    console.log("供应商接口完整响应:", responseData);
    if (responseData.flag === true) {
      // 假设 responseData.data.list 是供应商数组
      providerOptions.value = responseData.data.list || [];
      console.log('供应商原始数组:', providerOptions.value.slice())
      console.log("账单页面下拉供应商:", providerOptions.value);
      console.log('供应商原始数组:', JSON.parse(JSON.stringify(providerOptions.value)))

    } else {
      ElMessage.error(responseData.message || '获取供应商列表失败');
      providerOptions.value = [];
    }
  }).catch(err => {
    console.error("获取供应商列表出错:", err);
    ElMessage.error('网络请求失败');
    providerOptions.value = [];
  });
}

// 生成账单编码
const generateBillCode = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')

  return `BILL${year}${month}${day}${hours}${minutes}${seconds}`
}

// 提交表单
const submitForm = async () => {
  if (!billFormRef.value) return

  try {
    await billFormRef.value.validate()
    loading.value = true

    // 获取当前登录用户ID
    const loginUserStr = localStorage.getItem('loginUser')
    if (loginUserStr) {
      const user = JSON.parse(loginUserStr)
      billForm.createdBy = user.id
    }

    // 准备提交数据，排除 unitPrice 字段
    const submitData = {
      billCode: billForm.billCode,
      productName: billForm.productName,
      productDesc: billForm.productDesc,
      productUnit: billForm.productUnit,
      productCount: billForm.productCount,
      totalPrice: billForm.totalPrice,
      isPayment: billForm.isPayment,
      proName: billForm.proName,
      createdBy: billForm.createdBy
    }

    // 提交数据
    const response = await addBill(submitData)

    if (response.data && response.data.flag) {
      ElMessage.success('账单添加成功')
      resetForm()
      // 可以选择跳转到账单列表页面
      // router.push('/homepage/billList')
    } else {
      ElMessage.error(response.data?.message || '添加账单失败')
    }
  } catch (error) {
    console.error('添加账单错误:', error)
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('添加账单失败')
    }
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (billFormRef.value) {
    billFormRef.value.resetFields()
  }
  // 重新生成账单编码
  billForm.billCode = generateBillCode()
}

// 返回
const goBack = () => {
  router.go(-1)
}

// 页面加载时执行
onMounted(() => {
  fetchProviders()
  billForm.billCode = generateBillCode()
})
</script>

<template>
  <div class="bill-add-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>添加账单</span>
        </div>
      </template>

      <el-form :model="billForm" :rules="rules" ref="billFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="账单编码" prop="billCode">
              <el-input v-model="billForm.billCode" placeholder="请输入账单编码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="productName">
              <el-input v-model="billForm.productName" placeholder="请输入商品名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品单位" prop="productUnit">
              <el-select v-model="billForm.productUnit" placeholder="请选择商品单位" style="width: 100%">
                <el-option label="斤" value="斤"></el-option>
                <el-option label="包" value="包"></el-option>
                <el-option label="个" value="个"></el-option>
                <el-option label="件" value="件"></el-option>
                <el-option label="盒" value="盒"></el-option>
                <el-option label="瓶" value="瓶"></el-option>
                <el-option label="袋" value="袋"></el-option>
                <el-option label="箱" value="箱"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品数量" prop="productCount">
              <el-input-number
                  v-model="billForm.productCount"
                  :min="0.01"
                  :step="0.01"
                  :precision="2"
                  placeholder="请输入商品数量"
                  style="width: 100%"
                  @change="calculateTotalPrice"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单价" prop="unitPrice">
              <el-input-number
                  v-model="billForm.unitPrice"
                  :min="0.01"
                  :step="0.01"
                  :precision="2"
                  placeholder="请输入单价"
                  style="width: 100%"
                  @change="calculateTotalPrice"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总金额" prop="totalPrice">
              <el-input-number
                  v-model="billForm.totalPrice"
                  :min="0.01"
                  :step="0.01"
                  :precision="2"
                  placeholder="自动计算"
                  style="width: 100%"
                  disabled
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商" prop="proName">
              <el-select
                  v-model="billForm.proName"
                  placeholder="请选择供应商"
                  style="width: 100%"
                  filterable
              >
                <el-option
                    v-for="item in providerOptions"
                    :key="item.proCode"
                    :label="item.proName"
                    :value="item.proName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否付款" prop="isPayment">
              <el-radio-group v-model="billForm.isPayment">
                <el-radio :label="2">已付款</el-radio>
                <el-radio :label="1">未付款</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="商品描述" prop="productDesc">
          <el-input
              v-model="billForm.productDesc"
              type="textarea"
              :rows="3"
              placeholder="请输入商品描述"
          ></el-input>
        </el-form-item>

        <el-form-item style="text-align: center; margin-top: 30px;">
          <el-button type="primary" @click="submitForm" :loading="loading">
            <el-icon><Plus /></el-icon>
            添加账单
          </el-button>
          <el-button @click="resetForm" style="margin-left: 10px;">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button @click="goBack" style="margin-left: 10px;">
            <el-icon><Back /></el-icon>
            返回
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
.bill-add-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.box-card {
  max-width: 1000px;
  margin: 0 auto;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.el-form {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-button {
  min-width: 100px;
}

.el-card {
  background-color: #ffffff;
}

.el-input-number {
  width: 100%;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-select .el-input__inner) {
  border-radius: 4px;
}

:deep(.el-textarea__inner) {
  border-radius: 4px;
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}
</style>